<template>
  <div class="card">
    <DataActions @add="onAdd" @remove-batch="onRemoveBatch" />
    <DataTable
      ref="dataTable"
      :loading="false"
      :data="data"
      @edit-row="onEditRow"
      @remove-row="onRemove"
    >
      <el-table-column label="权限名" prop="code"></el-table-column>
      <el-table-column label="权限描述" prop="description"></el-table-column>
    </DataTable>
    <DataPagination v-model:page="page" v-model:limit="limit" :total="total" @change="onChange" />
  </div>
</template>

<script setup>
import DataActions from '@/components/datatable/DataActions.vue'
import DataTable from '@/components/datatable/DataTable.vue'
import DataPagination from '@/components/datatable/DataPagination.vue'
import { delPermission, getPermissions, delBatchPermission } from '@/http'
import { openErrorMessage } from '@/helper'
import { useTabStore } from '@/stores'

const data = ref([])
const page = ref(1)
const limit = ref(10)
const total = ref(0)
const tabStore = useTabStore()
const dataTable = ref()

const pull = async () => {
  const result = await getPermissions({
    page: page.value,
    limit: limit.value,
    sort_created_at: 'desc'
  })
  if (result) {
    data.value = result.data
    total.value = result.total
  }
}

// 删除某行
const onRemove = async (row) => {
  const result = await delPermission(row.id)
  if (result) {
    await pull()
  }
}

// 批量删除
const onRemoveBatch = async () => {
  const rows = dataTable.value.table.getSelectionRows()
  if (rows.length === 0) {
    openErrorMessage('未选中任何行')
    return
  }
  const ids = rows.map((row) => row.id).join(',')
  const result = await delBatchPermission(ids)
  if (result) {
    await pull()
  }
}

// page 或者 limit 更改会触发更新
const onChange = async () => {
  await pull()
}

// 点击编辑行
const onEditRow = (row) => {
  tabStore.toTab({
    name: 'permission-save',
    icon: 'Edit',
    title: '权限编辑',
    source: 'button',
    menu: 'permission',
    params: { id: row.id }
  })
}

// 点击新增
const onAdd = () => {
  tabStore.toTab({
    name: 'permission-add',
    icon: 'Edit',
    title: '权限新增',
    source: 'button',
    menu: 'permission'
  })
}

onMounted(pull)
</script>

<style lang="scss" scoped></style>
